package kiec.iss.eva.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import sun.security.x509.AlgorithmId;


public class X509Utils {
	
	public static boolean isSHA256(X509Certificate _X509Certificate) {
		boolean bSha256 = true;

		try {
//	        String strSigAlgName = _X509Certificate.getSigAlgName();
	        if (_X509Certificate.getSigAlgOID().equals(AlgorithmId.sha256WithRSAEncryption_oid.toString())) {
	        	bSha256 = true;
	        } else {
	        	bSha256 = false;
	        }
	        
		} catch (Exception e) {
        	bSha256 = false;
		}
		return bSha256;
	}
	
	public static boolean isSHA256(String strCertPath) {
		boolean bSha256 = true;
		
		File _file = new File(strCertPath);
		
        X509Certificate x509certificate = null;
        FileInputStream fileinputstream = null;
        CertificateFactory certificatefactory = null;
        
		try {
			fileinputstream = new FileInputStream(_file);
			certificatefactory = CertificateFactory.getInstance("X.509");
			x509certificate = (X509Certificate)certificatefactory.generateCertificate(fileinputstream);
			
			bSha256 = isSHA256(x509certificate);
			
		} catch (FileNotFoundException e) {
        	bSha256 = false;
		} catch (CertificateException e) {
        	bSha256 = false;
		} finally {
			if (fileinputstream != null) {
				try {
					fileinputstream.close();
				} catch (IOException e) {
				} finally {
					fileinputstream = null;
				}
			}
		}
		
		return bSha256;
	}
	
	public static void main(String[] s) {
		
		String strCertPath;
		
		strCertPath = "./test/cert/1024C/signCert.der";
		System.out.println(strCertPath + "->" + X509Utils.isSHA256(strCertPath));
		
		strCertPath = "./test/cert/2048C/signCert.der";
		System.out.println(strCertPath + "->" + X509Utils.isSHA256(strCertPath));
		
	}

}
